<template>
  <div class="txt-editor-container">
    <!-- 标题和操作按钮 -->
    <div class="editor-header">
      <h1 class="editor-title">文本编辑器</h1>
      <div class="button-group">
        <!-- <el-button
          type="primary"
          @click="saveText"
          :loading="isSaving"
          :disabled="!isContentChanged"
        >
          <el-icon v-if="!isSaving"><Save /></el-icon>
          <el-icon v-if="isSaving"><Loading /></el-icon>
          保存
        </el-button>
        <el-button type="warning" @click="fetchText" :loading="isLoading">
          <el-icon v-if="!isLoading"><Refresh /></el-icon>
          <el-icon v-if="isLoading"><Loading /></el-icon>
          重新加载
        </el-button> -->
        <el-button type="danger" @click="clearText" :disabled="!textContent">
          <el-icon><Delete /></el-icon>
          清空
        </el-button>
      </div>
    </div>

    <!-- 状态提示 -->
    <el-alert
      v-if="message"
      :message="message"
      :type="messageType"
      closable
      @close="message = ''"
      class="status-alert"
    />

    <!-- 文本编辑区域 -->
    <div class="editor-content">
      <el-input
        v-model="textContent"
        type="textarea"
        :rows="20"
        placeholder="加载文本中..."
        :disabled="isLoading || isSaving"
        @input="handleContentChange"
        class="text-editor"
      />
    </div>

    <!-- 底部信息 -->
    <div class="editor-footer">
      <div class="stats">
        <span>字符数: {{ textContent.length }}</span>
        <span>行数: {{ textContent.split("\n").length }}</span>
      </div>
      <div class="status">
        <span v-if="isContentChanged" class="status-changed">内容已修改</span>
        <span v-else class="status-saved">内容已保存</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import axios from "axios";
import { ref, onMounted, onUnmounted, onUpdated } from "vue";
// 修正图标导入方式
import { Refresh, Loading, Delete } from "@element-plus/icons-vue";
import { gmtTaskDownload } from "@/api/naturalRes";
import { ElMessage } from "element-plus";

const props = defineProps({
  txtDoc: {
    type: Object,
    default: {},
  },
});

// 文本内容
const textContent = ref("");
// 原始内容，用于判断是否有修改
const originalContent = ref("");
// 加载状态
const isLoading = ref(false);
// 保存状态
const isSaving = ref(false);
// 消息提示
const message = ref("");
// 消息类型
const messageType = ref<"success" | "warning" | "info" | "error">("info");
// 内容是否已修改
const isContentChanged = ref(false);

// 从后端获取文本内容
const fetchText = async () => {
  isLoading.value = true;
  message.value = "";
  console.log("txtDoc", props.txtDoc);
  try {
    const text: any = await gmtTaskDownload(
      props.txtDoc.newScriptId,
      props.txtDoc.paramValue
    );
    // 实际项目中替换为你的后端API地址
    // const response = await fetch('/api/text-file');

    // if (!response.ok) {
    //   throw new Error(`HTTP error! status: ${response.status}`);
    // }
    // const text = await response.text();
    // console.log('text',text);

    textContent.value = text;
    originalContent.value = text;
    isContentChanged.value = false;
    showMessage("文本加载成功", "success");
  } catch (error) {
    console.error("获取文本失败:", error);
    showMessage("获取文本失败，请稍后重试", "error");
  } finally {
    isLoading.value = false;
  }
};

// 保存文本内容到后端
const saveText = async () => {
  if (!isContentChanged.value) {
    showMessage("内容未修改，无需保存", "info");
    return;
  }

  isSaving.value = true;
  message.value = "";

  try {
    // 创建Blob对象
    const blob = new Blob([textContent.value], { type: "text/plain" });

    // 创建FormData对象
    const formData = new FormData();
    // 第一个参数是后端接收文件的参数名，第二个是Blob对象，第三个是文件名
    formData.append("file", blob, "edited-file.txt");
    formData.append("scriptId", props.txtDoc.newScriptId);
    formData.append("fileName", props.txtDoc.paramValue);
    const res = await axios({
      url: "http://10.222.125.103:18085/gmtScript/info/save/file",
      method: "post",
      headers: {
        "Content-Type": "multipart/form-data",
      },
      data: formData,
      timeout: 1000 * 20,
    });
    // await gmtTaskDownload()
    // 实际项目中替换为你的后端API地址
    // const response = await fetch('/api/text-file', {
    //   method: 'POST',
    //   headers: {
    //     'Content-Type': 'text/plain',
    //   },
    //   body: textContent.value,
    // });

    // if (!response.ok) {
    //   throw new Error(`HTTP error! status: ${response.status}`);
    // }

    originalContent.value = textContent.value;
    isContentChanged.value = false;
    showMessage("文本保存成功", "success");
  } catch (error) {
    console.error("保存文本失败:", error);
    showMessage("保存文本失败，请稍后重试", "error");
  } finally {
    isSaving.value = false;
  }
};

// 清空文本内容
const clearText = () => {
  if (textContent.value) {
    textContent.value = "";
    showMessage("文本已清空", "info");
  }
};

// 处理内容变化
const handleContentChange = () => {
  isContentChanged.value = textContent.value !== originalContent.value;
};

// 显示消息提示
const showMessage = (
  msg: string,
  type: "success" | "warning" | "info" | "error"
) => {
  message.value = msg;
  messageType.value = type;

  // 5秒后自动关闭消息
  setTimeout(() => {
    message.value = "";
  }, 5000);
};

// 监听页面关闭事件，提示未保存的更改
const handleBeforeUnload = (e: BeforeUnloadEvent) => {
  if (isContentChanged.value) {
    e.preventDefault();
    e.returnValue = "您有未保存的更改，确定要离开吗？";
    return e.returnValue;
  }
};

// 组件挂载时加载文本
onMounted(() => {
  fetchText();
  window.addEventListener("beforeunload", handleBeforeUnload);
});

// 组件卸载时移除事件监听
onUnmounted(() => {
  window.removeEventListener("beforeunload", handleBeforeUnload);
});

defineExpose({
  saveText,
  fetchText
});
</script>

<style scoped>
.txt-editor-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.editor-title {
  margin: 0;
  color: #333;
}

.button-group {
  display: flex;
  gap: 10px;
}

.status-alert {
  margin-bottom: 20px;
}

.editor-content {
  margin-bottom: 20px;
}

.text-editor {
  width: 100%;
  font-family: monospace;
  resize: vertical;
}

.editor-footer {
  display: flex;
  justify-content: space-between;
  color: #666;
  font-size: 14px;
  padding-top: 10px;
  border-top: 1px solid #eee;
}

.stats {
  display: flex;
  gap: 20px;
}

.status-changed {
  color: #e6a23c;
}

.status-saved {
  color: #67c23a;
}
</style>
